from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Optional
from app.services.audio_manager import audio_manager
from app.config.logging_config import get_logger

# 获取音频模块专用的日志记录器
logger = get_logger(__name__, "audio")

router = APIRouter(
    prefix="/audio",
    tags=["audio"]
)


class AudioPlayedRequest(BaseModel):
    """标记音频已播放的请求模型"""
    filename: Optional[str] = None
    audio_url: Optional[str] = None


class CleanupResponse(BaseModel):
    """清理操作响应模型"""
    success: bool
    message: str
    played_files_deleted: int
    old_files_deleted: int
    total_deleted: int
    remaining_files: int


class AudioStatsResponse(BaseModel):
    """音频统计信息响应模型"""
    total_files: int
    played_files: int
    unplayed_files: int
    total_size_bytes: int
    total_size_mb: float


@router.post("/mark-played")
async def mark_audio_played(request: AudioPlayedRequest):
    """标记音频文件为已播放
    
    Args:
        request: 包含文件名或音频URL的请求
        
    Returns:
        操作结果
    """
    try:
        if request.filename:
            audio_manager.mark_as_played(request.filename)
            logger.info(f"📝 通过文件名标记音频已播放: {request.filename}")
        elif request.audio_url:
            audio_manager.mark_as_played_by_url(request.audio_url)
            logger.info(f"📝 通过URL标记音频已播放: {request.audio_url}")
        else:
            raise HTTPException(status_code=400, detail="必须提供filename或audio_url")
        
        return {
            "success": True,
            "message": "音频文件已标记为已播放"
        }
        
    except Exception as e:
        logger.error(f"❌ 标记音频已播放失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"标记失败: {str(e)}")


@router.post("/cleanup", response_model=CleanupResponse)
async def cleanup_audio_files():
    """手动清理已播放和过期的音频文件
    
    Returns:
        清理操作结果
    """
    try:
        logger.info("🧹 收到手动清理音频文件请求")
        result = audio_manager.cleanup_all()
        
        return CleanupResponse(
            success=True,
            message=f"清理完成，删除了 {result['total_deleted']} 个文件",
            played_files_deleted=result['played_files_deleted'],
            old_files_deleted=result['old_files_deleted'],
            total_deleted=result['total_deleted'],
            remaining_files=result['remaining_files']
        )
        
    except Exception as e:
        logger.error(f"❌ 清理音频文件失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清理失败: {str(e)}")


@router.delete("/cleanup-played")
async def cleanup_played_files():
    """仅清理已播放的音频文件
    
    Returns:
        清理操作结果
    """
    try:
        logger.info("🧹 收到清理已播放音频文件请求")
        deleted_count = audio_manager.delete_played_files()
        
        return {
            "success": True,
            "message": f"清理完成，删除了 {deleted_count} 个已播放的文件",
            "deleted_count": deleted_count
        }
        
    except Exception as e:
        logger.error(f"❌ 清理已播放音频文件失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清理失败: {str(e)}")


@router.delete("/cleanup-old")
async def cleanup_old_files():
    """仅清理过期的音频文件
    
    Returns:
        清理操作结果
    """
    try:
        logger.info("🧹 收到清理过期音频文件请求")
        deleted_count = audio_manager.delete_old_files()
        
        return {
            "success": True,
            "message": f"清理完成，删除了 {deleted_count} 个过期的文件",
            "deleted_count": deleted_count
        }
        
    except Exception as e:
        logger.error(f"❌ 清理过期音频文件失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清理失败: {str(e)}")


@router.get("/stats", response_model=AudioStatsResponse)
async def get_audio_stats():
    """获取音频文件统计信息
    
    Returns:
        音频文件统计信息
    """
    try:
        stats = audio_manager.get_file_stats()
        
        return AudioStatsResponse(
            total_files=stats['total_files'],
            played_files=stats['played_files'],
            unplayed_files=stats['unplayed_files'],
            total_size_bytes=stats['total_size_bytes'],
            total_size_mb=stats['total_size_mb']
        )
        
    except Exception as e:
        logger.error(f"❌ 获取音频统计信息失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")


@router.post("/auto-cleanup/start")
async def start_auto_cleanup():
    """启动自动清理任务
    
    Returns:
        操作结果
    """
    try:
        await audio_manager.start_auto_cleanup()
        
        return {
            "success": True,
            "message": "自动清理任务已启动"
        }
        
    except Exception as e:
        logger.error(f"❌ 启动自动清理任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"启动失败: {str(e)}")


@router.post("/auto-cleanup/stop")
async def stop_auto_cleanup():
    """停止自动清理任务
    
    Returns:
        操作结果
    """
    try:
        await audio_manager.stop_auto_cleanup()
        
        return {
            "success": True,
            "message": "自动清理任务已停止"
        }
        
    except Exception as e:
        logger.error(f"❌ 停止自动清理任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"停止失败: {str(e)}")